import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus'
import useClientJS from '@/hooks/useClientJS';
const {fingerprint} = useClientJS();
import { useUserStore } from '@/stores/modules/user';
import router from '@/router';


// 创建axios实例
const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 10000, 
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json; charset=utf-8',
        'Client-Id': fingerprint
    }
})

let loading:any;
 
// request拦截器
request.interceptors.request.use(
    config => {
        loading = ElLoading.service({
            lock: true,
            text: 'Loading...',
            background: 'rgba(0, 0, 0, 0.7)',
        });
        const userStore = useUserStore();
        const token = userStore.token.length ? userStore.token : '';
        config.headers["Authorization"] = "Bearer " + token;
        return config
    },
    error => {
        Promise.reject(error)
    }
)
 
// response 拦截器
request.interceptors.response.use(
    response => {
        const { status } = response.data;
        loading.close();
        if (status === 200 || status === 201) 
            return response.data
        else 
            return Promise.reject(response.data);   
    },
    error => {  
        loading.close();
        console.log(error.response)
        switch (error.response.status) {
            case 401:
                ElMessage.error(error.response.data.message);
                router.push('/Login');
                break;
            case 404:
                ElMessage.error({message: '网络请求不存在'});
                break;
            case 500:
                ElMessage.error({message: '服务器出错了'});
                router.push('/Login');
                break;
            default:
                ElMessage.error({message: error.response.data.message});
                break;
        }
        
        return Promise.reject(error);
    }

    
)
export default request